package com.livepan.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.livepan.server.dao.FileDOMapper;
import com.livepan.server.dataobject.FileDO;
import com.livepan.server.dataobject.FileDOExample;
import com.livepan.server.error.BusinessException;
import com.livepan.server.error.EmBusinessError;
import com.livepan.server.service.model.FileModel;
import com.livepan.server.service.model.PageModel;
import com.livepan.server.utils.CopyUtil;
import com.livepan.server.utils.UUIDUtil;
import com.livepan.server.utils.ValidatorUtil;
import com.livepan.server.validator.ValidationResult;
import com.livepan.server.validator.ValidatorImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.cs.CharsetMapping;

import java.util.Date;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class FileService {
    @Autowired
    private FileDOMapper fileDOMapper;

    @Autowired
    private ValidatorImpl validator;

    public void list(PageModel pageModel) {
        PageHelper.startPage(pageModel.getPage(), pageModel.getSize());
        FileDOExample fileDOExample = new FileDOExample();
        List<FileDO> fileDOList = fileDOMapper.selectByExample(fileDOExample);
        PageInfo<FileDO> pageInfo = new PageInfo<>(fileDOList);
        pageModel.setTotal(pageInfo.getTotal());
        List<FileModel> fileModelList = fileDOList.stream().map(
                this::convertFileModelFromFileDO
        ).collect(Collectors.toList());
        pageModel.setList(fileModelList);
    }

    public void save(FileModel fileModel) throws BusinessException {
        ValidationResult validateResult = validator.validate(fileModel);
        if (validateResult.isHasError()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, validateResult.getErrMsg());
        }
        FileDO fileDO = CopyUtil.copy(fileModel, FileDO.class);
        if (fileDOMapper.selectByPrimaryKey(fileDO.getId()) == null) {
            this.insert(fileDO);
        } else {
            this.update(fileDO);
        }
    }

    private void insert(FileDO fileDO) {
        Date now = new Date();
        fileDO.setId(UUIDUtil.getShortUUID());
        fileDOMapper.insert(fileDO);
    }

    private void update(FileDO fileDO) {
        fileDOMapper.updateByPrimaryKey(fileDO);
    }

    public void delete(String id){
        fileDOMapper.deleteByPrimaryKey(id);
    }


    private FileModel convertFileModelFromFileDO(FileDO fileDO) {
        if (fileDO == null) {
            return null;
        }
        FileModel fileModel = new FileModel();
        BeanUtils.copyProperties(fileDO, fileModel);
        return fileModel;
    }
}
